#!/usr/bin/env python
# -*- coding: utf8 -*-

from __future__ import unicode_literals

import sqlite3


def dict_factory ( cursor, row ):
	dct = {}
	for idx, col in enumerate ( cursor.description ):
		dct [ col [ 0 ] ] = row [ idx ]
	return dct

from os3.dbm.dbman import BaseQueryBuilder

class Driver ( object ):
	def __init__ ( self ):
		self.db = None
		self.cursor = None

		self._last_query = ''
		self._last_query_params = tuple ()

	def connect ( self, ** kwargs ):
		self.db = sqlite3.connect ( kwargs.get ( 'db' ) )
		self.db.row_factory = dict_factory
		self.cursor = self.db.cursor ()

	def close ( self ):
		try:
			self.db.close ()
		except:
			pass

	def placeholders ( self, s ):
		return s

	def execute ( self, query, params = None ):
		if isinstance ( query, BaseQueryBuilder ):
			query, params = query.get_query_params ()

		if not params:
			params = tuple ()

		self._last_query = query
		self._last_query_params = params

		self.cursor.execute ( query, params )

	def fetchone ( self ):
		row = self.cursor.fetchone ()
		if not row:
			row = []
		return row

	def fetchall ( self ):
		return self.cursor.fetchall ()

	def _last_executed ( self ):
		if len ( self._last_query_params ):
			query = self._last_query.replace ( '?', "'%s'" ) % tuple ( self._last_query_params )
		else:
			query = self._last_query

		return query

	def insert_id ( self ):
		return self.cursor.lastrowid


class QueryBuilder ( BaseQueryBuilder ):
	pass
